package com.example.toy.core.utils;

import com.example.toy.core.version.ToyVersion;
import org.apache.commons.io.FilenameUtils;
import org.apache.hadoop.fs.Path;

/**
 * TablePathDefine
 *
 * @author shenbing
 * @date 2021/12/21
 */
public class ToyPathDefine {

  public static final String META_FOLDER_NAME = ".toy";
  public static final String ARCHIVE_FOLDER_NAME = "archives";
  public static final String COMMITS_FOLDER_NAME = "commits";
  public static final String INDEX_FOLDER_NAME = "indexes";

  public static final String META_PROPERTY_FILE = "table.properties";

  /**
   * 表元信息配置文件路径
   *
   * @param root
   * @return
   */
  public static Path getTableConfigFilePath(Path root) {
    return new Path(getMetaDirPath(root), META_PROPERTY_FILE);
  }

  /**
   * 表元信息文件夹路径
   *
   * @param root
   * @return
   */
  public static Path getMetaDirPath(Path root) {
    return new Path(root, META_FOLDER_NAME);
  }

  /**
   * 表提交历史文件夹
   *
   * @param root
   * @return
   */
  public static Path getCommitDirPath(Path root) {
    return new Path(getMetaDirPath(root), COMMITS_FOLDER_NAME);
  }

  /**
   * 归档文件夹
   *
   * @param root
   * @return
   */
  public static Path getArchiveDirPath(Path root) {
    return new Path(getMetaDirPath(root), ARCHIVE_FOLDER_NAME);
  }

  /**
   * 分区锁文件路径
   *
   * @param partitionPath
   * @return
   */
  public static Path getPartitionLockPath(Path partitionPath) {
    return new Path(partitionPath, "partition.lock");
  }

  /**
   * 表锁文件路径
   *
   * @param basePath
   * @return
   */
  public static Path getTableLockPath(Path basePath) {
    return new Path(basePath, "table.lock");
  }

  /**
   * 索引文件夹路径
   *
   * @param basePath
   * @return
   */
  public static Path getIndexDirPath(Path basePath) {
    return new Path(basePath, INDEX_FOLDER_NAME);
  }

  /**
   * 判断是否是toy表数据文件
   *
   * @param path 文件路径
   * @return
   */
  public static boolean isToyDataFile(Path path) {
    return path.getName().startsWith("toy");
  }

  /**
   * 判断是否是toy表基本数据文件
   *
   * @param path 文件路径
   * @return
   */
  public static boolean isBaseDataFile(Path path) {
    return path.getName().startsWith("toy-base");
  }

  /**
   * 判断是否是toy表增量数据文件
   *
   * @param path 文件路径
   * @return
   */
  public static boolean isDeltaDataFile(Path path) {
    return path.getName().startsWith("toy-delta");
  }

  /**
   * 从数据文件名中获取版本号
   *
   * <p>toy-base-versionxxxx-taskxxxx.parquet
   *
   * @param path
   * @return
   */
  public static ToyVersion extractVersion(Path path) {
    String name = path.getName();
    String baseName = FilenameUtils.getBaseName(name);
    String[] split = baseName.split("-");
    if (split.length != 4) {
      throw new IllegalStateException("Error file path to extract toy version: " + path);
    }
    return new ToyVersion(Long.parseLong(split[2]));
  }
}
